/**
 * 新开历史医嘱
 */
var histroyIndex;
function lishiyizhu()
{
	$("#lishiyizhu_btn").attr("disabled",true);
	laytplUrl(myurl + "/module/history.html", [],
			function(data, html) {
				$("#history_table").html(html);
				histroyIndex = layer.open({
					  type: 1,
					  title:'历史医嘱',
					  area: ['80%', '70%'], //宽高
					  content: html,
					  success: function()
					{
						  $("#lishiyizhu_btn").removeAttr("disabled");
						  if($("#history_table").html()=="")
							{
								//加载jqgrid
								showHistroyAdvice();
								$("#history_cancle").on("click",function(){
									layer.close(histroyIndex);
								})
							}
					}
					});
	}
	);
}
function showHistroyAdvice(){
	 var arr = [];
	 $.ajax({
		 url : rootUrl + "/doctoradvice/patientsuccessivedoctoradvicerecord",
		 type : "post",
		 dataType : 'json',
		 async : false,
		 data :
			{
				"EmpID": bce01,
				"lVAA01": $("#vaa01").val(),
			    "lVAF04" : 1,
			    "lCheck" : 0,
			    "productid" : 100,
			    "programid" : 105002,
			    "paramno" : 233,
			    "currPage" : 1,
			    "pageSize" : 30
			},
			success : function(data){
				debugger;
				var temp = data.list;
				for(var i=0;i<temp.length;i++){
					var dataObj=temp[i];
					dataObj.data_info = JSON.stringify(temp[i]);
					arr.push(dataObj);
				}
				HistroyAdviceInit(data.list);
			}
		
	 })
}

//按同组校对
var selectSameGroupRowEnd = true;//判断选择同组的行有没有结束
function checkSameGroup(ischecked,tname,theRow,theId){
    var dd =  $('#'+tname).jqGrid("getDataIDs");

    var groupArr = [];
    for(var i=0;i<dd.length;i++){
        var row =  $('#'+tname).jqGrid("getRowData", dd[i]);
        if(dd[i]!=theId&&row.vaf01!=theRow.vaf01&&row.vaa05==theRow.vaa05&&row.vaf59==theRow.vaf59&&row.cbm01==theRow.cbm01&&row.vaf11==theRow.vaf11){
            groupArr.push(dd[i]);
        }
    };
    selectSameGroupRowEnd = false;
    for(var j= 0,jLen = groupArr.length;j<jLen;j++){
        $('#'+tname).jqGrid('setSelection',groupArr[j]);
    }
    selectSameGroupRowEnd = true;
};
function HistroyAdviceInit(arr)
{
	var tabe_id = "history_table";
	var tname = "history_table";
	layer.msg('加载中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*400}); 
//	$('#history_table_container').resize(function(){
//		$("#history_table").setGridWidth($("#history_table_container").width()*1);
//	});
	jQuery('#history_table').GridUnload();
	jQuery("#history_table").jqGrid(
	{
	datatype: 'local', 
	data:arr,
	colModel :
	[
	{
	label : " ",
	name : 'copy',
	width:"110",
	 cellattr: function(rowId, tv, rawObject, cm, rdata) {
         return 'id='+tname+'_copy' + rowId;
     }
	},
	{
	label:"时间",
	name : 'vaf36',
	width:"250"
	},
	{
	label : "医嘱内容",
	name : 'vaf22n',
	width:"500"
	},
	{
	label : "皮试",
	name : 'vaf25'
	},
	{
	label : "用法",
	name : 'fusage',
	width:"350",
	 cellattr: function(rowId, tv, rawObject, cm, rdata) {
		 
         return 'id='+tname+'_fusage' + rowId;
     }
	},
	{
	label : "总量",
	name : 'vaf21'
	},
	{
	label : "单位",
	name : 'fgross'
	},
	{
	label : "医生嘱托",
	name : 'vaf23'
	},
	{
	label : "执行科室",
	name : 'nbck03'
	},
	{
	label : "附加执行",
	name : 'bck03c'
	},
	{
	label : "执行性质",
	name : 'vaf58'
	},
	{
	label : "计价性质",
	name : 'vaf31'
	},
	{
	label : "用药目的",
	name : 'biw02'
	},
	{
	label : "医嘱备注",
	name : 'vaf55'
	}, 
	{
	label : "开嘱医生",
	name : 'bce03a'
	},
	{
		name : 'bby01',
		hidden:true
	},
	{
		name : 'bda01',
		hidden:true
	},
	{
		name : 'vaf01',
		hidden:true
	},
	{
		name : 'vaf22',
		hidden:true
	},
	{
		name : 'bbx01',
		hidden:true
	},
	{
		name : 'vaf32',
		hidden:true
	},
	{
		name : 'cbm01',
		hidden:true
	}
	,
	{
		name : 'data_info',
		hidden:true
	},
	{
		name : 'vaf15',
		hidden:true
	},
	{
		name : 'vaf59',
		hidden:true
	}
	],
//	 sortname : 'cbm01',
//     sorttype : 'desc',
	viewrecords : true,
	multiselect : true,
	height : 'auto',
	width : 'auto',
	autowidth : true,
//	forceFit:true,
//    shrinkToFit:true,
	rownumbers : true,
	rowNum : arr.length,
//	grouping:true,
//   	groupingView : 
//   	{
//   		groupField : ['cbm01'],
//   		groupColumnShow : [false],
//   		groupText : ['<b>{0}</b>']
//   	},
   	loadComplete : function(data)
	{
   		debugger;
		if (data.rows.length<1)
		{
			var $tr = $('#' + tabe_id).find('tbody>tr:last');
			var len = $tr.find('td').length;
			$("#" + tabe_id).html('<tr><td colspan="' + parseInt(len) + '" style="text-align:left;">没有历史医嘱数据！</td></tr>');
		}else{
			
			var ids = jQuery("#history_table").jqGrid('getDataIDs');
			for (var i = 0; i < ids.length; i++)
			{
				var cl = ids[i];
				var copyInput = "<button class='btn btn-min btn-white' onclick='copyRow(this)' >复制</button>";
				jQuery("#history_table").jqGrid('setRowData', ids[i],
						{
					copy : copyInput
						});
			}
		}
	}, gridComplete: function() {
        //在gridComplete调用合并方法,合并单元格
        var gridName = "history_table";
        merger(gridName, 'fusage'); //用法
        merger(gridName, 'copy'); //单选框
	},
	 onSelectRow : function(id,status)
     {
		 if(!status){
             var groupTr = $('#'+tname+' tr#'+id).prevAll('.jqgroup')[0];
             $(groupTr).find('[type="checkbox"]').prop('checked',false);
         };
         if(!selectSameGroupRowEnd){
             return;
         }
         var row = $("#"+tname).jqGrid("getRowData", id);
         if(selectSameGroupRowEnd){
             checkSameGroup(status,tname,row,id);
         }
     }
	});
}

function copyRow(that){
	debugger;
	layer.msg('复制中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500,skin: 'layui-layer-msg16'});
	var rowid = $(that).parents("tr").attr("id");
	var flag = $(that).parents("td").attr("rowspan");
	if(flag>1){
		var curXuhao
		var lastVal = $("#west_medicine_table tbody").find("tr").last().find(".xiyao_yznr").val();
		if(lastVal){
			 curXuhao = $("#west_medicine_table tbody").find("tr").last().index()+1;
		}else{
			
			curXuhao = $("#west_medicine_table tbody").find("tr").last().index();
		}
		for (var i = rowid;i<(parseInt(rowid)+parseInt(flag));i++){
			copyExcute(i);
		}
		editTongzu(curXuhao);
		layer.close(histroyIndex);
	}else{
		
		copyExcute(rowid)
	}
	
}

function copyExcute(rowid){
	debugger
	 layer.msg('复制中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500,skin: 'layui-layer-msg16'});
	var rowdata = $("#history_table").jqGrid("getRowData", rowid);
	var row = JSON.parse($("#history_table").jqGrid("getRowData", rowid).data_info);
//	var row = $("#history_table").jqGrid("getRowData", rowid);
	var bda01 = row.bda01;
	row.type = "histroy";
	row.vaf01 = rowdata.vaf01;
	if(bda01 =='L'){
		$('#new_order_list a[href^="#Jianyan"]').last().tab('show');
		addJianyanCyxm(row);
	}
	else if(bda01 =='E'){
		$('#new_order_list a[href^="#Jiancha"]').last().tab('show');
		addJianchaCyxm(row)
	}
	else if(bda01 =='1' || bda01=="2"){
		typeClick("Xiyao");
	 $('#new_order_list a[href^="#Xiyao"]').last().tab('show');
	 histroyXiyaoYibao(row);
	}
	else if(bda01 =='8'){
		typeClick("Zhongyao");
		$('#new_order_list a[href^="#Zhongyao"]').last().tab('show');
//		adviceZhongyao(row);
		editzhongyaoAdvice(row);
	}
	else if(bda01 =='S'){
		typeClick("Shoushu");
		$('#new_order_list a[href^="#Shoushu"]').last().tab('show');
		editShoushuAdvice(row);
	}
	else if(("1238SE".indexOf(bda01) < 0 && row.vaf01a == 0 && (row.vaf32 == 0||!row.vaf32))){
		$('#new_order_list a[href^="#Zhiliao"]').last().tab('show');
		addZhiliaoCyxm(row);
	}
	layer.close(histroyIndex);
}
function adviceZhongyao(dataObj){
	var zyjiangfa;
	var editzhongyaoobj ={};
	var bda01 = dataObj.bda01;
	var arr =[];
	if (bda01 == "3" || bda01 == "8")
	{
		var url = rootUrl + "/doctoradviceeditor/getVaf1Byvaf01a";
		var params ={};
		params.vaf01 = dataObj.vaf01;
		$.get(url, params, function(data)
		{
			debugger;
			var list = data.list;
			for (var i = 0; i < list.length; i++)
			{
				if (list[i].bda01 == 'T')
				{
					zyjiangfa = list[i].vaf22;
				}
				else if (list[i].bda01 == '3')
				{
					arr.push(list[i]);
				}

			}
			dataObj = $.extend(dataObj,
			{
				'zyjiangfa' : zyjiangfa
			});
			editzhongyaoobj['data'] = dataObj;
			for (var i = 0; i < arr.length; i++)
			{
				editzhongyaoobj['list'] = arr[i];
				addZhongyaoCyxm(editzhongyaoobj);
			}
		});
	}
}
function copyMutAdvice(that){
	debugger;
	$(that).attr("disabled",true);
	var $prevTrRow 
	var selectedIds = $("#history_table").jqGrid("getGridParam", "selarrrow");
	if(selectedIds.length>0){
		 layer.msg('复制中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500,skin: 'layui-layer-msg16'});
			for (var i = 0;i<selectedIds.length;i++){
				var row = JSON.parse($("#history_table").jqGrid("getRowData", selectedIds[i]).data_info);
//				var row = $("#history_table").jqGrid("getRowData", selectedIds[i]);
				if(i>0){
					 $prevTrRow = JSON.parse($("#history_table").jqGrid("getRowData", selectedIds[i-1]).data_info);
//					 $prevTrRow = $("#history_table").jqGrid("getRowData", selectedIds[i-1]);
				}
				var bda01 = row.bda01;
				row.type = "histroy";
				if(bda01 =='L'){
					$('#new_order_list a[href^="#Jianyan"]').last().tab('show');
					addJianyanCyxm(row);
				}
				else if(bda01 =='E'){
					$('#new_order_list a[href^="#Jiancha"]').last().tab('show');
					addJianchaCyxm(row)
				}
				else if(bda01 =='1' || bda01=="2"){
					typeClick("Xiyao");
					$('#new_order_list a[href^="#Xiyao"]').last().tab('show');
					 histroyXiyaoYibao(row);
					if($prevTrRow&&($prevTrRow.cbm01 ==row.cbm01) ){
						editTongzu('',row.cbm01);
					}
				}
				else if(bda01 =='8'){
					$('#new_order_list a[href^="#Zhongyao"]').last().tab('show');
//					adviceZhongyao(row);
					editzhongyaoAdvice(row);
				}
				else if(bda01 =='S'){
					typeClick("Shoushu");
					$('#new_order_list a[href^="#Shoushu"]').last().tab('show');
					editShoushuAdvice(row);
				}
				else if(("1238SE".indexOf(bda01) < 0 && row.vaf01a == 0 && (row.vaf32 == 0||!row.vaf32))){
					 $('#new_order_list a[href^="#Zhiliao"]').last().tab('show');
					 addZhiliaoCyxm(row);
				}
			}
//			if(bda01 =='1' || bda01=="2"){
//				editTongzu();
//			}
			$(that).attr("disabled",false);
		layer.close(histroyIndex);
	}else {
		layer.msg("请选择要复制的医嘱",{time:2000,icon:0,skin: 'layui-layer-msg0'});
		$(that).attr("disabled",false);
	}
}

/**
 * 公共同组方法
 * @param gridName
 * @param CellName
 */
function merger(gridName, CellName) {
	debugger;
    //得到显示到界面的id集合
    var mya = $("#" + gridName + "").getDataIDs();
    var length = mya.length;
    for (var i = 0; i < length; i++) {
        //从上到下获取一条信息
        var before = $("#" + gridName + "").jqGrid('getRowData', mya[i]);
        //定义合并行数
        var rowSpanTaxCount = 1;
        if(CellName == "copy"){
        	for (j = i + 1; j <= length; j++) {
        		//和上边的信息对比 如果值一样就合并行数+1 然后设置rowspan 让当前单元格隐藏
        		var end = $("#" + gridName + "").jqGrid('getRowData', mya[j]);
        		if (before[CellName] == end[CellName]&&before['cbm01']==end['cbm01']&&before['vaf11']==end['vaf11']&&(before['bda01']==1||before['bda01']==2)) {
        			rowSpanTaxCount++;
        			$("#" + gridName + "").setCell(mya[j], CellName, '', { display: 'none' });
        		} else {
        			rowSpanTaxCount = 1;
        			break;
        		}
        		$("#" +gridName+"_"+ CellName + mya[i]).attr("rowspan", rowSpanTaxCount);
        	}

        }else{
        	
        	for (j = i + 1; j <= length; j++) {
        		//和上边的信息对比 如果值一样就合并行数+1 然后设置rowspan 让当前单元格隐藏
        		var end = $("#" + gridName + "").jqGrid('getRowData', mya[j]);
        		if (before[CellName] == end[CellName]&&before['cbm01']==end['cbm01']&&before['vaf11']==end['vaf11']&&(before['bda01']==1||before['bda01']==2)&&before['vaf59']==end['vaf59']) {
        			rowSpanTaxCount++;
        			$("#" + gridName + "").setCell(mya[j], CellName, '', { display: 'none' });
        		} else {
        			rowSpanTaxCount = 1;
        			break;
        		}
        		$("#" +gridName+"_"+ CellName + mya[i]).attr("rowspan", rowSpanTaxCount);
        	}
        }
    }
}

//历史医嘱赋值判断是否医保限制用药

function histroyXiyaoYibao(row){
	var rowArr = [];
	rowArr.push(row);
	var tabId = "Xiyao";
	if (valueArr["p_100_105002_420"]=="1"){  //启用医保用药限制提示
		if (valueArr["p_9999_9999_114"]=="1"){//只针对医保病人
			if($("#patient_bdp02").text()!="自费"){
				histroyYibaoData(rowArr,tabId);
			}else{
				addXiyaoCyxm(row);
			}
			
		}else{
			histroyYibaoData(rowArr,tabId);
		}
		
	}else{
		addXiyaoCyxm(row);
	}
}


function histroyYibaoData(row,tabId){
	debugger
	 $.when( 
			 getVeh02(row)
         ).done(function (list) { 
        	 debugger
        	 $('#new_order_list a[href="#'+tabId+'"]').last().tab('show');
        	 $('#new_order_list a[href="#'+tabId+'"]').last().trigger("click");
        	 var editRestult = [],conbindata;
        	 for(var k =0; k<row.length;k++){
        		 for(var i=0;i<list.length;i++){
        			 if(list[i].vaf01 == row[k].vaf01){
        				 conbindata = $.extend(row[k],list[i]);
        			 }
        		 }
    			 addXiyaoCyxm(conbindata||row[k]);
     		 }
         });
}

















